package com.hqhsc.module.manage.activity.service;

import com.hqhsc.core.cache.CacheKey;
import com.hqhsc.module.common.dao.CommonDao;
import com.hqhsc.module.common.service.CommonService;
import com.hqhsc.module.common.service.FileService;
import com.hqhsc.module.common.service.ManageMemcacdedClient;
import com.hqhsc.module.common.service.QrCodeService;
import com.hqhsc.module.log.service.LogService;
import com.hqhsc.module.manage.activity.dao.ActivityManageDao;
import com.hqhsc.module.manage.activity.domain.Activity;
import com.hqhsc.module.manage.activity.domain.ActivityChannelDetail;
import com.hqhsc.module.manage.activity.domain.ActivityTemplet;
import com.hqhsc.module.manage.channel.dao.ChannelManageDao;
import com.hqhsc.module.manage.channel.domain.Channel;
import com.hqhsc.utils.DateUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.text.DecimalFormat;
import java.util.*;

/**
 *
 * @author jiangyin
 */
@Service
public class ActivityManageService {

	static Logger logger = LoggerFactory.getLogger(ActivityManageService.class);

	@Autowired
	private ManageMemcacdedClient memcachedClient;
	@Autowired
	private ActivityManageDao activityManageDao;
    @Autowired
    private ChannelManageDao channelManageDao;
    @Autowired
    private CommonService commonService;
    @Autowired
    private FileService fileService;
    @Autowired
    private CommonDao commonDao;
    @Autowired
    private Properties appProps;
    @Autowired
    private QrCodeService qrCodeService;
    @Autowired
    private LogService logService;

    public Map<String , Object> getActivityList(long org_id , String activity_name , int activity_type , String orderby_request , int start , int size) {

        String orderby = null;
        String orderby_type = null;
        if(StringUtils.isNotEmpty(orderby_request)) {
            orderby = orderby_request.split(",")[0];
            orderby_type = orderby_request.split(",")[1];
        }

        long total = this.activityManageDao.getActivityCount(org_id, activity_name , activity_type);
        List<Activity> activity_list = this.activityManageDao.getActivityList(org_id, activity_name, activity_type , orderby , orderby_type , start, size);

        for(Activity activity : activity_list) {
            activity.setBegin_time(activity.getBegin_time().substring(0 , activity.getBegin_time().length()-5));
            activity.setEnd_time(activity.getEnd_time().substring(0, activity.getEnd_time().length() - 5));
        }

        Map<String , Object> map = new HashMap<String, Object>();
        map.put("total" , total);
        map.put("activity_list" , activity_list);
        return map;
    }

    public Map<String , Object> getActivityTempletList(int start, int size) {
        int total = this.activityManageDao.getActivityTempletCount();
        List<ActivityTemplet> result = this.activityManageDao.getActivityTempletList(start , size);
        Map<String , Object> map = new HashMap<String, Object>();
        map.put("total" , total);
        map.put("activity_templet_list" , result);
        return map;
    }

    public List<Channel> getChannelList() {
        return this.channelManageDao.getChannelList(0 , null , -1 , null , null , 0 , 1000);
    }

    public int doAddActivity(String activity_name , int templet_id , int type , String title , String desc , String content , String flow , String place , String begin_time_str , String end_time_str , String[] channel_id_arg , HttpServletRequest request , CommonsMultipartFile file_upload , long userid) {
        try{
            String file_path_db = "";
            if(!file_upload.isEmpty()) {
                //文件上传
                String base_path = request.getSession().getServletContext().getRealPath("/");
                String file_path= appProps.getProperty("activity.import.dbpath");
                String save_path = base_path + file_path;
                String file_sys_name = UUID.randomUUID().toString();
                Map<String , String> map = this.fileService.uploadFile(file_upload , save_path , file_sys_name);
                file_path_db = file_path + "/" + file_sys_name + map.get("ext_name");
            }

            long activity_id = commonDao.getNextVal("ActivitySeq");
            Date begin_time = DateUtil.string2Date(begin_time_str , "yyyy-MM-dd HH:mm:ss");
            Date end_time = DateUtil.string2Date(end_time_str , "yyyy-MM-dd HH:mm:ss");

            //生成活动现场签名二维码
            String base_path = request.getSession().getServletContext().getRealPath("/");
            String file_path = appProps.getProperty("activity.sign.qrcode.download.realpath");
            String file_name = activity_id + "_sign_qr_" + DateUtil.getDate(new Date(), "yyyy-MM-dd") + ".png";
            String db_path = file_path + file_name;
            String path = base_path + db_path;
            String qr_code_url = appProps.get("base.url") + "hqhsc/activity/sign/index";
            this.qrCodeService.encoderQRCode(qr_code_url + "?aid=" + activity_id , path , "png" , 10);

            int result = this.activityManageDao.insertActivity(activity_id , activity_name , templet_id , type , title , desc , content , flow , place , begin_time , end_time , file_path_db , db_path , userid);
            if(result > 0 && channel_id_arg.length > 0) {
                //批量跟新渠道的活动数，活动数+1
                this.activityManageDao.batchUpdateChannelActivityNum(channel_id_arg , 1);
                //批量插入渠道对应活动关系
                this.activityManageDao.batchInsertChannelActivity(channel_id_arg , activity_id);
            }

            this.logService.insertLog(userid , "增加活动"+activity_id , "");
            logger.info("manage activity doAddActivity success"+activity_id);

            return result;
        } catch (Exception e) {
            logger.error(e.getMessage() , e);
            return 0;
        }
    }

    public List<ActivityChannelDetail> getActivityChannelDetail(long activity_id) {
        return this.activityManageDao.getActivityChannelDetailByActivityId(activity_id);
    }

    public List<ActivityChannelDetail> getActivityChannelDetail(HttpServletRequest request , long activity_id , String activity_name , String qr_code_url) {
        List<ActivityChannelDetail> activityChannelDetailList = this.activityManageDao.getActivityChannelDetailByActivityId(activity_id);

        DecimalFormat df = new DecimalFormat("0.00");//格式化小数
        for(ActivityChannelDetail activityChannelDetail : activityChannelDetailList) {

            if(activityChannelDetail.getPoint_count() > 0) {
                double avg = Double.valueOf(activityChannelDetail.getSpread_cost()) / activityChannelDetail.getPoint_count();
                activityChannelDetail.setPoint_cost_avg(Double.valueOf(df.format(avg)));
            } else {
                activityChannelDetail.setPoint_cost_avg(Double.valueOf(activityChannelDetail.getSpread_cost()));
            }

            if(activityChannelDetail.getSignup_count() > 0) {
                double avg = Double.valueOf(activityChannelDetail.getSpread_cost()) / activityChannelDetail.getSignup_count();
                activityChannelDetail.setSignup_cost_avg(Double.valueOf(avg));
            } else {
                activityChannelDetail.setSignup_cost_avg(Double.valueOf(activityChannelDetail.getSpread_cost()));
            }

            //生成二维码，再插入数据库
            if(StringUtils.isEmpty(activityChannelDetail.getQr_code())) {
                String base_path = request.getSession().getServletContext().getRealPath("/");
                String file_path = appProps.getProperty("activity.channel.qrcode.download.realpath");
                String file_name = activity_id + "_" + activityChannelDetail.getChannel_id();

                String db_path = file_path + file_name + "-qr-" + DateUtil.getDate(new Date() , "yyyy-MM-dd") + ".png";
                String path = base_path + db_path;
                logger.info("base_path is: "+base_path+" db_path is: "+db_path);
                this.qrCodeService.encoderQRCode(qr_code_url + "?aid=" + activity_id + "&cid=" + activityChannelDetail.getChannel_id() , path , "png" , 10);

                activityChannelDetail.setQr_code(db_path);

                //将二维码地址，插入数据库
                this.activityManageDao.updateActivityChannelQrCode(activityChannelDetail.getId() , db_path);
            }
        }
        return activityChannelDetailList;
    }

    public List<Activity> getActivityListByIds(String activity_ids) {
        List<Activity> activity_list = new ArrayList<Activity>();
        String[] activity_id_args = activity_ids.split(",");
        for(int i = 0 ; i < activity_id_args.length ; i++) {
            int activity_id = Integer.valueOf(activity_id_args[i]);
            Activity activity = this.commonService.getSysActivityById(activity_id);
            List<ActivityChannelDetail> activity_channel_detail_list = this.activityManageDao.getActivityChannelDetailByActivityId(activity_id);
            activity.setActivity_channel_detail_list(activity_channel_detail_list);

            activity_list.add(activity);
        }
        return activity_list;
    }

    /**
     * 活动上下线
     * @param activity_id
     * @param desc_status 目标状态：0/1
     * @return
     */
    public void updateStatus(long activity_id , int desc_status , long userid) {
        this.activityManageDao.updateActivityStatus(activity_id , desc_status);

        //状态更新了，删除缓存
        String key = CacheKey.getActivityKey(activity_id);
        this.memcachedClient.delete(key);

        this.logService.insertLog(userid , "活动上下线,desc_status:"+desc_status , "");
    }


    public int activityDoEdit(long activity_id , String activity_name , int type , String title , String desc , String content , String flow , String place , String begin_time_str , String end_time_str , String[] channel_id_arg , long userid) {
        try{
            //该活动原有对应的渠道信息
            List<ActivityChannelDetail> activityChannelDetailList = this.getActivityChannelDetail(activity_id);

            Date begin_time = DateUtil.string2Date(begin_time_str , "yyyy-MM-dd HH:mm:ss");
            Date end_time = DateUtil.string2Date(end_time_str , "yyyy-MM-dd HH:mm:ss");
            int result = this.activityManageDao.updateActivity(activity_id, activity_name, type, title, desc, content, flow, place, begin_time, end_time);

            if(result > 0 && channel_id_arg.length > 0) {
                //状态更新了，删除缓存
                String key = CacheKey.getActivityKey(activity_id);
                this.memcachedClient.delete(key);

                //批量更新原渠道的活动数，-1
                List<String> channel_id_list = new ArrayList<String>();
                for(ActivityChannelDetail acd : activityChannelDetailList) {
                    channel_id_list.add(String.valueOf(acd.getChannel_id()));
                }
                String[] aaa = channel_id_list.toArray(new String[channel_id_list.size()]);

                this.activityManageDao.batchUpdateChannelActivityNum(aaa , -1);
                //删除渠道对应活动关系
                this.activityManageDao.deleteActivityChannelByChannelId(activity_id);

                 //批量跟新渠道的活动数，活动数+1
                this.activityManageDao.batchUpdateChannelActivityNum(channel_id_arg, 1);
                //批量插入渠道对应活动关系
                this.activityManageDao.batchInsertChannelActivity(channel_id_arg , activity_id);
            }

            this.logService.insertLog(userid , "更新活动"+activity_id , "");
            return result;
        } catch (Exception e) {
            logger.error(e.getMessage() , e);
            return 0;
        }
    }


}
